package com.contract.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.contract.common.enums.FaceCheckCode;
import com.contract.common.error.BizException;
import com.contract.common.error.JsonReturnCode;
import com.contract.pojo.dto.FaceMatchModel;
import com.contract.pojo.dto.FaceMatchResult;
import com.contract.pojo.dto.IdCardModel;
import com.contract.pojo.dto.IdCardResult;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度人脸识别工具类
 */
@Slf4j
public class AuthUtil {

    /**
     * 人像对比
     *
     * @param imgPath  图片路径
     * @param cardPath 身份证路径
     */
    public static boolean comparingFace(String imgPath, String cardPath) {
        List<FaceMatchModel> list = new ArrayList<>();
        FaceMatchModel mode = new FaceMatchModel();
        String base = FileUtil.imageToBase64(imgPath);
        if (base == null) {
            return false;
        }
        mode.setImage(base);
        mode.setImageType("BASE64");
        mode.setFaceType("LIVE");
        mode.setQualityControl("LOW");
        mode.setLivenessControl("LOW");
        list.add(mode);
        mode = new FaceMatchModel();
        base = FileUtil.imageToBase64(cardPath);
        if (base == null) {
            return false;
        }
        mode.setImage(base);
        mode.setImageType("BASE64");
        mode.setFaceType("CERT");
        mode.setQualityControl("LOW");
        mode.setLivenessControl("NONE");
        list.add(mode);

        String s = HttpUtil.doPost(getMatchUrl(), JSON.toJSONString(list));
        FaceMatchResult faceMatchResult = JSON.parseObject(s, FaceMatchResult.class);
        log.info("comparingFace:" + JSON.toJSONString(faceMatchResult));
        FaceCheckCode.Node node = FaceCheckCode.CODE_MAP.get(faceMatchResult.getErrorCode());
        if (node != null) {
            throw new BizException(JsonReturnCode.BIZ_FAIL, node.getAdvice());
        }
        Double score = faceMatchResult.getResult().getScore();
        return score != null && score >= 80;
    }

    /**
     * 解析身份证
     *
     * @param path 身份证图片的路径
     */
    public static IdCardResult cardAnalysis(String path, String type) {
        try {
            IdCardModel model = new IdCardModel();
            String base = FileUtil.imageToBase64(path);
            if (base == null) {
                throw new BizException(JsonReturnCode.CARD_ANALYSIS_ERROR);
            }
            model.setImage(URLEncoder.encode(base, "UTF-8"));
            model.setIdCardSide(type);
            Map<String, String> map = new HashMap<>();
            map.put("Content-Type", "application/x-www-form-urlencoded");
            String s = HttpUtil.doPost(getCardUrl(), model.toJson(), map);
            IdCardResult result = JSON.parseObject(s, IdCardResult.class);
            log.info("cardAnalysis:" + JSON.toJSONString(result));
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new BizException(JsonReturnCode.CARD_ANALYSIS_ERROR);
        }
    }

    public static String getValue(String key, Map<String, IdCardResult.Words> wordsResult) {
        IdCardResult.Words words = wordsResult.get(key);
        if (words == null) {
            return "";
        }
        return words.getWords();
    }

    public static LocalDate getValueDate(String key, Map<String, IdCardResult.Words> wordsResult) {
        IdCardResult.Words words = wordsResult.get(key);
        if (words == null) {
            return null;
        }
        String w = words.getWords();
        int year = Integer.parseInt(w.substring(0, 4));
        int month = Integer.parseInt(w.substring(4, 6));
        int day = Integer.parseInt(w.substring(6));
        return LocalDate.of(year, month, day);
    }

    public static String getMatchUrl() {
        return Constant.MATCH_URL + getAuth();
    }

    public static String getCardUrl() {
        return Constant.ID_CARD_URL + getAuth();
    }

    /**
     * 获取权限token
     */
    public static String getAuth() {
        String url = String.format(Constant.AUTH_URL, Constant.CLIENT_ID, Constant.CLIENT_SECRET);
        String result = HttpUtil.doGet(url);
        JSONObject parse = JSON.parseObject(result);
        return parse.getString("access_token");
    }

}